
//
//  XHMessageRootViewController.m
//  MessageDisplayExample
//
//  Created by HUAJIE-1 on 14-4-26.
//  Copyright (c) 2014年 嗨，我是曾宪华(@xhzengAIB)，曾加入YY Inc.担任高级移动开发工程师，拍立秀App联合创始人，热衷于简洁、而富有理性的事物 QQ:543413507 主页:http://zengxianhua.com All rights reserved.
//

#import "XHMessageRootViewController.h"

#import "XHFoundationCommon.h"


#import "XHDemoWeChatMessageTableViewController.h"
#import "XHCustomCellDemoMessageTableViewController.h"

#import "UIView+XHBadgeView.h"

#import "SDImageCache.h"
#import "Conversation.h"
#import "WSJConversion.h"
#import "WSJObserveNewChatTool.h"
#import "Constants.h"
#import "WSJConversionCell.h"
#import "UITableViewRowAction+JZExtension.h"
#import "EMCDDeviceManager.h"
@interface XHMessageRootViewController ()

//@property (nonatomic, strong) XHPopMenu *popMenu;
@property (nonatomic,  assign) NSInteger currentNumOfConversitons;


@end

@implementation XHMessageRootViewController

#pragma mark - Action

- (void)enterMessage {
    XHDemoWeChatMessageTableViewController *demoWeChatMessageTableViewController = [[XHDemoWeChatMessageTableViewController alloc] init];
    [self.navigationController pushViewController:demoWeChatMessageTableViewController animated:YES];
}

- (void)enterCustomCellMessage {
    XHCustomCellDemoMessageTableViewController *customCellDemoMessageTableViewController = [[XHCustomCellDemoMessageTableViewController alloc] init];
    [self.navigationController pushViewController:customCellDemoMessageTableViewController animated:YES];
}
/*
- (void)enterNewsController {
    XHNewsTableViewController *newsTableViewController = [[XHNewsTableViewController alloc] init];
    [self pushNewViewController:newsTableViewController];
}

- (void)enterQRCodeController {
    XHQRCodeViewController *QRCodeViewController = [[XHQRCodeViewController alloc] init];
    [self pushNewViewController:QRCodeViewController];
}

 */



- (instancetype)init{
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNewMessage:) name:WechatNewMessageInforNotificaiton object:nil];
    }
    return self;
}

#pragma mark -收到新信息
- (void)receiveNewMessage:(NSNotification *)not{
   
    NSArray *arr = not.userInfo[@"ConversionAndMessage"];
    
    WSJConversion *conversion =arr[0];
//    XHMessage *message =arr[1];
    defineWeakSelf;
    
    if (weakSelf.dataSource.count ==0 ) {
        [weakSelf.dataSource addObject:conversion];
        dispatch_sync(dispatch_get_main_queue(), ^{
          [self.tableView reloadData];
        });
            
     
        return;
    }
      
    [self.dataSource enumerateObjectsUsingBlock:^(WSJConversion  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.rowid ==conversion.rowid) {
            [weakSelf.dataSource replaceObjectAtIndex:idx withObject:conversion];
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            });
            return ;
           
        }
        if (weakSelf.dataSource.count ==0 && idx ==weakSelf.dataSource.count) {
            [weakSelf.dataSource addObject:conversion];
            dispatch_sync(dispatch_get_main_queue(), ^{
                
                [weakSelf.tableView reloadData];
               
            });

        }
        
    }];
    
   

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];

}

#pragma mark -增加 一句
- (void)showMenuOnView:(UIBarButtonItem *)buttonItem {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        WSJConversion *entity = [[WSJConversion alloc] init];
        LKDBHelper *h =[WSJConversion getUsingLKDBHelper];
        entity.patientName = @"asd";
        entity.nurseId = [[[WCCoreDataStore shareStore] getAccount] stringId];
        entity.avatarUrl = @"http://v1.qzone.cc/avatar/201406/08/18/35/53943c70b54e9227.jpeg!180x180.jpg";
        entity.detailText = @"上海胜事信息科技有限公司是医疗界最具实力的公司";
        entity.unread = @1;
        entity.timestamp = [NSDate date];
        [h insertToDB:entity];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataSource addObject:entity];
            [self.tableView reloadData];
        });
    });


}
#pragma mark - Propertys
/*
- (XHPopMenu *)popMenu {
    if (!_popMenu) {
        NSMutableArray *popMenuItems = [[NSMutableArray alloc] initWithCapacity:6];
        for (int i = 0; i < 5; i ++) {
            NSString *imageName;
            NSString *title;
            switch (i) {
                case 0: {
                    imageName = @"contacts_add_newmessage";
                    title = @"发起群聊";
                    break;
                }
                case 1: {
                    imageName = @"contacts_add_friend";
                    title = @"添加朋友";
                    break;
                }
                case 2: {
                    imageName = @"contacts_add_scan";
                    title = @"扫一扫";
                    break;
                }
                case 3: {
                    imageName = @"contacts_add_photo";
                    title = @"拍照分享";
                    break;
                }
                case 4: {
                    imageName = @"contacts_add_voip";
                    title = @"视频聊天";
                    break;
                }
                default:
                    break;
            }
            XHPopMenuItem *popMenuItem = [[XHPopMenuItem alloc] initWithImage:[UIImage imageNamed:imageName] title:title];
            [popMenuItems addObject:popMenuItem];
        }
        
        WEAKSELF
        _popMenu = [[XHPopMenu alloc] initWithMenus:popMenuItems];
        _popMenu.popMenuDidSlectedCompled = ^(NSInteger index, XHPopMenuItem *popMenuItems) {
            if (index == 2) {
                [weakSelf enterQRCodeController];
            }else if (index == 0 ) {
                [weakSelf addContactForGroup];
            }
        };
    }
    return _popMenu;
}
*/
- (void)addContactForGroup {
    /*
    //建立100个测试数据
    NSMutableArray *items = [NSMutableArray array];
    //网上拉的昵称列表，请忽视非主流。
    NSArray *names = @[@"貓眼无敌",
                       @"涽暗丶芉咮帘",
                       @"一个人搁浅",
                       @"时间像沙漏一样穿过瓶颈。",
                       @"朶，莪哋囡亾-",
                       @"得不到的在乎",
                       @"请不要留恋 .",
                       @"草bian的戒指",
                       @"y1旧、狠轻狂",
                       @"阿娇的垃圾的死了快回答了",
                       @"Angel、葬爱",
                       @"花无心。",
                       @"別致の情緒",
                       @"最近的心跳╰",
                       @"莪想莪慬嘚",
                       @"祂誓〃：毅丹",
                       @"╃渼锝Ъú橡話♂",
                       @"盗梦空间",
                       @"飘流瓶丶逆反",
                       @"①個〆国产纯货ル",
                       @"请你别敷衍ら",
                       @"乱挺爱4@",
                       @"︶￣浮动",
                       @"无规则 Rules°",
                       @"——拽、杀。",
                       @"1③⒋4.⒈",
                       @"殇、箌茈僞祉",
                       ];
    
    NSArray *avatarURLs = @[
                            @"http://v1.qzone.cc/avatar/201406/08/18/50/53943ff25f268523.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/35/53943c70b54e9227.jpeg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/51/539440434b1c7139.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/48/53943f8408bea913.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/48/53943f8ae0384052.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/49/53943fcbb3be9306.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/38/53943d320f616180.png!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/47/53943f469a925760.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/46/53943f1a6b0ee418.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/47/53943f5ec2961034.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/47/53943f486e7ae921.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/45/53943ebae083b101.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/45/53943ec67c849838.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/45/53943ed21aa91813.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/45/53943ec4449f3999.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/43/53943e4e5733a368.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/43/53943e5d120b6630.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/41/53943dc293e22403.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/43/53943e6188616462.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/43/53943e3b42266017.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/41/53943dea86fa9728.png!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/42/53943e2c732d6796.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/40/53943da63ea18098.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/41/53943dec0428e119.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/41/53943dea86fa9728.png!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/41/53943dec0428e119.jpg!180x180.jpg",
                            @"http://v1.qzone.cc/avatar/201406/08/18/42/53943e2c732d6796.jpg!180x180.jpg",
                            ];
    
    for (NSUInteger i=0; i<names.count; i++) {
        MultiSelectItem *item = [[MultiSelectItem alloc]init];
        item.imageURL = [NSURL URLWithString:avatarURLs[i]];
        item.name = names[i];
        if (i==10||(i>4&&i<8)) {
            item.selected = YES;
        }
        if (i==6||i==9) {
            item.disabled = YES;
        }
        [items addObject:item];
    }
    MultiSelectViewController *vc = [[MultiSelectViewController alloc]init];
    vc.items = items;
    
    XHBaseNavigationController *navVC = [[XHBaseNavigationController alloc]initWithRootViewController:vc];
    [self.navigationController presentViewController:navVC animated:YES completion:nil];
     */
}


#pragma mark - DataSource

- (void)loadDataSource {
    
    ///获取 LKTest 类使用的 LKDBHelper
    LKDBHelper* globalHelper = [XHMessage getUsingLKDBHelper];
    defineWeakSelf;
    
//    从数据库获取会话数据
    [globalHelper search:[WSJConversion class] where:nil orderBy:nil offset:0 count:0 callback:^(NSMutableArray *array) {
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            weakSelf.dataSource = [array mutableCopy];
            [weakSelf.tableView reloadData];
        });
       
        
    }];;
    
    
    
    
    
    
//    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSInteger pageSize = 10;
//        
//        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
//        NSFetchRequest *request = [[NSFetchRequest alloc] init];
//        request.entity = [NSEntityDescription entityForName:@"Conversation" inManagedObjectContext:[WCCoreDataStore shareStore].context];
//        NSPredicate *predicate = [NSPredicate
//                                  predicateWithFormat:@"(nurseId = %@)", [[[WCCoreDataStore shareStore] getAccount] stringId]];
//        
//        [request setPredicate:predicate];
//        NSError *error = nil;
//        [request setFetchLimit:pageSize];
//        
//        /*   //从数据库里每次加载500条数据来筛选数据
//         [request setFetchBatchSize:10];
//         */
//        //读取数据库的游标偏移量，从游标开始读取数据
//        //    [request setFetchOffset:currentCount];
//        
//        request.sortDescriptors = @[sort];
//        
//        NSArray *result = [[WCCoreDataStore shareStore].context executeFetchRequest:request error:&error];
//        NSArray *finalresult = [[result reverseObjectEnumerator] allObjects];
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            self.dataSource = [finalresult mutableCopy];
//            [self.tableView reloadData];
//        });
//    });
}

#pragma mark - Life Cycle

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    [self.tableView registerNib:[UINib nibWithNibName:@"WSJConversionCell" bundle:nil] forCellReuseIdentifier:@"WSJConversionCell"];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showMenuOnView:)];
    [self.navigationController.navigationBar setTintColor:[UIColor redColor]];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"PageBack"]style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    
    self.tableView.frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight -64);
    self.tableView.tableFooterView =[UIView new];
    [self.view addSubview:self.tableView];
    
    [self loadDataSource];
}
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableView DataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    static NSString *cellIdentifier = @"cellIdentifier";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
//    cell.imageView.layer.cornerRadius =10;
//    cell.imageView.layer.masksToBounds = YES;
//    
//    if (!cell) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
//        cell.textLabel.font = [UIFont systemFontOfSize:15];
//        
//        cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
//        
//    }
//    WSJConversion *conversation = self.dataSource[indexPath.row];
//    if (indexPath.row < self.dataSource.count) {
//        if (!indexPath.row) {
//            
//            cell.textLabel.text = [conversation.patientName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//            cell.imageView.image = [UIImage imageNamed:@"avatar"];
//            cell.detailTextLabel.text = [conversation.detailText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        } else {
//            cell.textLabel.text = [conversation.patientName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];;
//            cell.detailTextLabel.text = [conversation.detailText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];;
//            [cell.imageView setImageWithURL:[NSURL URLWithString:conversation.avatarUrl] placeholderImage:[UIImage imageNamed:@"avatar"]];
////            cell.imageView.image = [UIImage imageNamed:@"avatar"];
//        }
//    }
//    
//    
//    
//    if ([conversation.unread integerValue] > 0) {
//        cell.textLabel.textColor = [UIColor blackColor];
//        UILabel *countLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 16, 16)];
//        countLabel.adjustsFontSizeToFitWidth = YES;
//        countLabel.font = [UIFont systemFontOfSize:10];
//        
//        countLabel.textColor = [UIColor whiteColor];
//        countLabel.backgroundColor =[UIColor redColor];
//        countLabel.textAlignment = NSTextAlignmentCenter;
//        countLabel.layer.cornerRadius = 8;
//        countLabel.layer.masksToBounds = YES;
//        cell.accessoryView = countLabel;
//        countLabel.text =[NSString stringWithFormat:@"%@",conversation.unread];
//        [cell.imageView setupCircleBadge];
//    } else {
//        cell.accessoryView =nil;
//        [cell.imageView destroyCircleBadge];
//    }
    
 
    
    
//    if (indexPath.row == 4) {
//        cell.textLabel.textColor = cell.detailTextLabel.textColor = [UIColor colorWithRed:0.097 green:0.633 blue:1.000 alpha:1.000];
//    } else if (indexPath.row == 0) {
//        cell.textLabel.textColor = [UIColor colorWithRed:0.429 green:0.187 blue:1.000 alpha:1.000];
//    } else if (indexPath.row == 6) {
//        cell.textLabel.textColor = cell.detailTextLabel.textColor = [UIColor colorWithRed:1.000 green:0.222 blue:0.906 alpha:1.000];
//    } else {
//        cell.textLabel.textColor = cell.detailTextLabel.textColor = [UIColor grayColor];
//    }
    
    WSJConversionCell *cell =[tableView dequeueReusableCellWithIdentifier:@"WSJConversionCell" forIndexPath:indexPath];
    cell.model =self.dataSource[indexPath.row];
    
    return cell;
}

#pragma mark - UITableView Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 59;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    if (!indexPath.row) {
////        [self enterNewsController];
//    } else if (indexPath.row == 6) {
//        //[self enterCustomCellMessage];
//    } else {
//        [self enterMessage];
//    }
    
    
    
    XHDemoWeChatMessageTableViewController *demoWeChatMessageTableViewController = [[XHDemoWeChatMessageTableViewController alloc] initWithChatInfo:self.dataSource[indexPath.row]];
    [self.navigationController pushViewController:demoWeChatMessageTableViewController animated:YES];
}
#pragma mark -适配8.0 以前版本
- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
     defineWeakSelf;
    WSJConversion *model =self.dataSource[indexPath.row];
    LKDBHelper *db = [WSJConversion getUsingLKDBHelper];
    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除"  handler:^(UITableViewRowAction * _Nullable action, NSIndexPath * _Nullable indexPath) {
        [weakSelf  setEditing:false animated:YES];
        [weakSelf.dataSource removeObject:model];
        [model deleteToDB];
        [db deleteWithClass:[XHMessage class] where:[NSString stringWithFormat:@"conversionId = %d",model.rowid] callback:^(BOOL result) {
            
        }];
        [weakSelf.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    }];
    return @[action1];
}

@end
